<template>
  <el-dialog v-model="visible" title="新增方案" width="400">
    <el-form :model="config" ref="formEl" :rules="rules" label-width="100px" :inline="false" class="mt-4">
      <el-form-item label="方案名称" prop="name">
        <el-input v-model="config.name"></el-input>
      </el-form-item>

      <el-form-item label="自重比载" prop="w">
        <el-input v-model="config.w"></el-input>
      </el-form-item>

      <el-form-item label="水平张力" prop="H">
        <el-input v-model="config.H"></el-input>
      </el-form-item>

      <el-form-item label="子导线数量" prop="ziDaoxianNum">
        <el-input v-model="config.ziDaoxianNum"></el-input>
      </el-form-item>

      <el-form-item label="相数量" prop="xiangNum">
        <el-input v-model="config.xiangNum"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit(formEl)">立即创建</el-button>
        <el-button @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import useCalculateStore from '@/states/useCalculateStore'
import usePlanStore from '@/states/usePlanStore'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

const emit = defineEmits(['change'])

const route = useRoute()
const formEl = ref<FormInstance>()
const visible = defineModel()
const calculateStore = useCalculateStore()
const planStore = usePlanStore()
const lindId = ref(+route.params.id)

interface CaclConfig {
  name: string
  w: number
  H: number
  ziDaoxianNum: number
  xiangNum: number
}

const config = ref<CaclConfig>({
  name: '',
  w: 0,
  H: 0,
  ziDaoxianNum: 0,
  xiangNum: 0,
})

const rules = reactive<FormRules<CaclConfig>>({
  name: [
    {
      required: true,
      message: '请输入方案名称',
      trigger: ['blur'],
    },
  ],
  w: [
    {
      required: true,
      message: '请输入自重比载',
      trigger: ['blur'],
    },
  ],
  H: [
    {
      required: true,
      message: '请输入水平张力',
      trigger: ['blur'],
    },
  ],
  ziDaoxianNum: [
    {
      required: true,
      message: '请输入子导线数量',
      trigger: ['blur'],
    },
  ],
  xiangNum: [
    {
      required: true,
      message: '请输入相数量',
      trigger: ['blur'],
    },
  ],
})

async function onSubmit(formEl: FormInstance | undefined) {
  if (!formEl) return
  await formEl.validate().then(async (valid) => {
    if (valid) {
      const { data } = await calculateStore.calc({
        id: lindId.value,
        name: config.value.name,
        w: config.value.w,
        H: config.value.H,
        ziDaoxianNum: config.value.ziDaoxianNum,
        xiangNum: config.value.xiangNum,
      })
      emit('change', data.id)
      await planStore.all({ id: lindId.value })

      visible.value = false
      ElMessage.success('计算成功')
    }
  })
}
</script>

<style></style>
